package com.example.sunmiv1.dialog;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.LoginEntity;
import com.example.sunmiv1.entity.UserRepaymentInfo;
import com.example.sunmiv1.entity.VipListBean;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;

public class RepayDialog extends BaseDialog {


    @BindView(R.id.setCreditMoney_title)
    TextView setCreditMoneyTitle;
    @BindView(R.id.repayDialog_close)
    ImageView repayDialogClose;
    @BindView(R.id.repayDialog_online)
    TextView repayDialogOnline;
    @BindView(R.id.repayDialog_balance)
    TextView repayDialogBalance;
    @BindView(R.id.repayDialog_money)
    TextView repayDialogMoney;
    @BindView(R.id.repayDialog_other)
    TextView repayDialogOther;
    @BindView(R.id.repayDialog_otherList)
    ListView repayDialogOtherList;
    Unbinder unbinder;

    private String vid = "";
    private String code = "";
    private int payType = 1;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private List<UserRepaymentInfo.DataBean.ListBean> list;

    private String text = "";
    private LoginEntity loginEntity;
    private List<LoginEntity.DataBean.OtherPayListBean> otherList = new ArrayList<>();

    private int payWay_index = 9999;
    private String payFlag = "";
    private VipListBean.InfoBean infoBean = null;
    private double totalMoney = 0;

    public static RepayDialog newInstance(double totalMoney, String vid, List<UserRepaymentInfo.DataBean.ListBean> list) {
        RepayDialog fragment = new RepayDialog();
        Bundle bundle = new Bundle();
        bundle.putDouble("money", totalMoney);
        bundle.putString("vid", vid);
        bundle.putSerializable("list", (Serializable) list);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.repay_dialog;
    }


    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            // 下面這些設置必須在此方法(onStart())中才有效
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0xff000000));
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            Window window = dialog.getWindow();
            // 如果不設置這句代碼, 那麼彈框就會與四邊都有一定的距離
            window.setBackgroundDrawableResource(android.R.color.transparent);
            window.setWindowAnimations(R.style.DialogFromBottom);// 設置動畫
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = dm.widthPixels;
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.BOTTOM;
            window.setAttributes(setLayout(params));
        }
    }

    @Override
    protected void initData() {
        aCache = ACache.get(getContext());
        loadingDialog = new LoadingDialog(getContext());
//        vid = getArguments().getString("vid");
        text = aCache.getAsString("loginInfo");
        loginEntity = GsonUtils.JsonToBean(text, LoginEntity.class);
        payFlag = loginEntity.getData().getMerchantConfig().getOther_pay();
        if (loginEntity.getData().getOtherPayList().size() > 0) {
            if ("1".equals(aCache.getAsString("other_pay"))) {
                for (int i = 0; i < loginEntity.getData().getOtherPayList().size(); i++) {
                    otherList.add(loginEntity.getData().getOtherPayList().get(i));
                }
            }
        }
        list = (List<UserRepaymentInfo.DataBean.ListBean>) getArguments().getSerializable("list");
        totalMoney = getArguments().getDouble("money");
        setOtherPayListAdapter();
    }

    @Override
    protected void initListener() {
        repayDialogOtherList.setOnItemClickListener((parent, view, position, id) -> {
            payWay_index = position;
            repayDialogOtherList.setVisibility(View.GONE);
            repayPort();
        });
    }

    private void setOtherPayListAdapter() {
        ArrayAdapter<LoginEntity.DataBean.OtherPayListBean> adapter =
                new ArrayAdapter<LoginEntity.DataBean.OtherPayListBean>(getContext(), android.R.layout.simple_list_item_1, otherList) {
                    @Override
                    public View getDropDownView(int pos, @Nullable View convertView, @NonNull ViewGroup parent) {
                        @SuppressLint("ViewHolder") View view = ((Activity) getContext()).getLayoutInflater().inflate(android.R.layout.simple_list_item_single_choice, parent, false);
                        final TextView text = view.findViewById(android.R.id.text1);
                        text.setText(otherList.get(pos).getName());
                        text.setGravity(Gravity.CENTER);
                        text.setTextSize(14);
                        return view;
                    }

                    @NonNull
                    @Override
                    public View getView(int pos, @Nullable View convertView, @NonNull ViewGroup parent) {
                        @SuppressLint("ViewHolder") View view = ((Activity) getContext()).getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
                        final TextView text = view.findViewById(android.R.id.text1);
                        text.setText(otherList.get(pos).getName());
                        text.setTextSize(14);
                        text.setGravity(Gravity.CENTER);
                        return view;
                    }
                };
        repayDialogOtherList.setAdapter(adapter);
    }

    @OnClick({R.id.repayDialog_close, R.id.repayDialog_online, R.id.repayDialog_balance, R.id.repayDialog_money, R.id.repayDialog_other})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.repayDialog_close:
                dismiss();
                break;
            case R.id.repayDialog_online:
                repayDialogOtherList.setVisibility(View.GONE);
                payType = 1;
                startQrCode();
                break;
            case R.id.repayDialog_balance:
                repayDialogOtherList.setVisibility(View.GONE);
                payType = 3;
                if (TextUtils.isEmpty(vid)) {
                    VipLoginDialog.newInstance()
                            .callback(o -> {
                                infoBean = (VipListBean.InfoBean) o;
                                vid = infoBean.getId();
                                repayDialogBalance.setText(getString(R.string.repayDialogTip) + infoBean.getBalance() + ")");
                            })
                            .startShow(getFragmentManager(), "")
                            .setCancelable(false);
                } else {
                    if (infoBean == null) {
                        Toast.makeText(getContext(), "請先登錄會員", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Double.parseDouble(infoBean.getBalance()) >= totalMoney) {
                        repayPort();
                    } else {
                        Toast.makeText(getContext(), "餘額不足，請選擇其他還款方式", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.repayDialog_money:
                repayDialogOtherList.setVisibility(View.GONE);
                payType = 2;
                repayPort();
                break;
            case R.id.repayDialog_other:
                payType = 4;
                if (otherList.size() > 0) {
                    if (repayDialogOtherList.getVisibility() == View.VISIBLE) {
                        repayDialogOtherList.setVisibility(View.GONE);
                    } else {
                        repayDialogOtherList.setVisibility(View.VISIBLE);
                    }
                } else {
                    repayPort();
                }
                break;
        }
    }

    /**
     * 賒賬還款
     */
    private void repayPort() {
        JSONArray jsonArray = new JSONArray();
        for (UserRepaymentInfo.DataBean.ListBean bean : list) {
            if (bean.isCheck()) {
                if (TextUtils.isEmpty(bean.getRepaymentMoney())) {
                    Toast.makeText(getContext(), "請輸入還款金額", Toast.LENGTH_SHORT).show();
                    return;
                }
                JSONObject json = new JSONObject();
                try {
                    json.put("id", bean.getId());
                    json.put("back_pay_money", bean.getRepaymentMoney());
                    jsonArray.put(json);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        if (jsonArray.length() == 0) {
            Toast.makeText(getContext(), "請先選擇要還款的訂單", Toast.LENGTH_SHORT).show();
            return;
        }
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("arr", jsonArray);
            jsonObject.put("pay_type", payType);
            switch (payType) {
                case 1:
                    jsonObject.put("code", code);
                    break;
                case 3:
                    jsonObject.put("vid", vid);
                    break;
                case 4:
                    if (otherList.size() > 0) {
                        if (payWay_index != 9999) {
                            jsonObject.put("other_pay_id", otherList.get(payWay_index).getId());
                        }
                    }
                    break;
            }
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("editor_type", "1");
            } else {
                jsonObject.put("editor_type", "2");
            }
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(getContext(), Common.REPAY_PORT, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(getContext(), json.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        dismiss();
                        callback.success("");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });
    }

    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(getContext(), CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(getContext(), "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            code = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            repayPort();
        }
    }

}
